﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Windows;
using System.Windows.Data;
using System.Windows.Input;
using Lib.Helper;
using MSIACCSL2.Command;
using MSIACCSL2.GroupServices;
using MSIACCSL2.Views.Warehouse;
using MSIACCSL2.WarehouseServices;
using DeleteCompletedEventArgs = MSIACCSL2.WarehouseServices.DeleteCompletedEventArgs;
using GetListByCriteriaCompletedEventArgs = MSIACCSL2.WarehouseServices.GetListByCriteriaCompletedEventArgs;
using GetListCompletedEventArgs = MSIACCSL2.WarehouseServices.GetListCompletedEventArgs;
using SaveCompletedEventArgs = MSIACCSL2.WarehouseServices.SaveCompletedEventArgs;
using Search = MSIACCSL2.Views.Warehouse.Search;
using Warehouse = WcfService1.DTO.WarehouseDTO;

namespace MSIACCSL2.ViewModels
{
    public class WarehouseViewModel : ViewModelBase
    {
        #region Delegates

        public delegate void Completed(Object param);

        #endregion

        private static string OrderType;
        private static string PropertySort;
        public static Mode mode;
        private static Warehouse _group;
        private static Add frmAdd;

        public static Completed OnSearchCompleted;
        private readonly WarehouseServicesClient client;
        private readonly ValidationHandler validationHandler;
        private int CurrentPage;
        private GroupServicesClient GroupClient;
        private ObservableCollection<int> Pages;
        private bool _IsBusy;
        private PagedCollectionView _Warehouses;
        private PagedCollectionView _pageSources;
        private Search frmSearch;


        public WarehouseViewModel()
        {
            if (!DesignerProperties.IsInDesignTool)
            {
                client = new WarehouseServicesClient();
                GroupClient = new GroupServicesClient();
                OnPageChanged = new DelegateCommand(PageIndexChanged, CanPageIndexChanged);
                Save = new DelegateCommand(SaveWarehouse, CanSave);
                New = new DelegateCommand(NewWarehouse, CanNew);
                Edit = new DelegateCommand(EditWarehouse, CanEdit);
                Unload = new DelegateCommand(Release, CanUnload);
                SearchCommand = new DelegateCommand(SearchWarehouse, CanSearch);
                SearchResultCommand = new DelegateCommand(SearchResult, CanSearchResult);
                validationHandler = new ValidationHandler();

                //Kalo lagi di Edit jangan diload Datanya tar nimpa

                if (mode == Mode.Edit || mode == Mode.Search || mode == Mode.Add)
                {
                }
                else
                {
                    GetList(1, null);
                }
            }
        }

        public PagedCollectionView Warehouses
        {
            get { return _Warehouses; }

            private set
            {
                if (Warehouses == value) return;
                _Warehouses = value;

                int i = (CurrentPage*30);
                foreach (object Warehouse in Warehouses)
                {
                    i += 1;

                    ((Warehouse) Warehouse).No = i;
                }

                FirePropertyChanged("Warehouses");
                Warehouses.CollectionChanged += Group_CollectionChanged;
            }
        }


        public PagedCollectionView PageSources
        {
            get { return _pageSources; }
            private set
            {
                if (PageSources == value) return;
                _pageSources = value;
                FirePropertyChanged("PageSources");
            }
        }


        public bool IsBusy
        {
            get { return _IsBusy; }
            internal set
            {
                _IsBusy = value;
                FirePropertyChanged("IsBusy");
            }
        }

        public long RecordCount { get; set; }

        //Buat binding ke child form waktu mau edit
        public static Warehouse Warehouse
        {
            get { return _group; }
            private set
            {
                if (Warehouse == value) return;
                _group = value;
                FirePropertyChanged2("Warehouse");
            }
        }


        public ICommand OnPageChanged { get; set; }
        public ICommand Save { get; set; }
        public ICommand New { get; set; }
        public ICommand Edit { get; set; }
        public ICommand Unload { get; set; }
        public ICommand SearchCommand { get; set; }
        public ICommand SearchResultCommand { get; set; }

        public string Error
        {
            get { return null; }
        }

        public string this[string columnName]
        {
            get
            {
                if (validationHandler.BrokenRuleExists(columnName))
                {
                    return validationHandler[columnName];
                }
                return null;
            }
        }

        public void Complete(Object param)
        {
            OnSearchCompleted(param);
        }

        private void Group_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            if (((PagedCollectionView) sender).SortDescriptions.Count > 0)
            {
                if (((PagedCollectionView) sender).SortDescriptions[0].PropertyName.ToLower() == "no") return;

                PropertySort = ((PagedCollectionView) sender).SortDescriptions[0].PropertyName;
                if (string.IsNullOrEmpty(OrderType))
                {
                    OrderType = "ASC";
                }
                else
                {
                    OrderType = OrderType == "ASC" ? OrderType = "DESC" : OrderType = "ASC";
                }
                GetList(1, PropertySort);
            }
        }


        public void SaveWarehouse(Object Warehouse)
        {
            ((Warehouse) Warehouse).created_by = GlobalVar.User.UserID;
            ((Warehouse) Warehouse).modified_by = GlobalVar.User.UserID;
            client.SaveCompleted += client_SaveCompleted;
            client.SaveAsync((Warehouse) Warehouse);
        }

        private void client_SaveCompleted(object sender, SaveCompletedEventArgs e)
        {
            client.SaveCompleted -= client_SaveCompleted;
            if (e.Result)
            {
                MessageBox.Show("Success");
                frmAdd.DialogResult = true;
                Refresh();
            }
        }


        public void GetList(int? page, string sortProp)
        {
            IsBusy = true;
            client.GetListCompleted += client_GetListCompleted;
            client.GetListAsync(page ?? 1, sortProp, OrderType);
        }

        private void client_GetListCompleted(object sender, GetListCompletedEventArgs e)
        {
            RecordCount = e.recordCount;
            if (PageSources == null) CreatePageNumber();
            client.GetListCompleted -= client_GetListCompleted;
            Warehouses = new PagedCollectionView(e.Result);
            IsBusy = false;
            Complete(this);
        }


        private void NewWarehouse(Object param)
        {
            mode = Mode.Add;
            Warehouse = new Warehouse();
            frmAdd = new Add();
            frmAdd.Show();
        }


        public static void EditWarehouse(Object param)
        {
            mode = Mode.Edit;
            Warehouse = (Warehouse) param;
            frmAdd = new Add();
            frmAdd.Show();
        }


        private void SearchWarehouse(Object param)
        {
            mode = Mode.Search;
            frmSearch = new Search();
            frmSearch.Show();
        }


        private void SearchResult(Object param)
        {
            //Dictionary<String, Object> criteria = new Dictionary<string, object>();
            //frmSearch = (Search)param;
            //if (!String.IsNullOrEmpty(frmSearch.txtKode.Text)) criteria.Add("kode_persediaan", frmSearch.txtKode.Text);
            //if (!String.IsNullOrEmpty(frmSearch.txtNama.Text)) criteria.Add("nama_persediaan", frmSearch.txtNama.Text);
            //if (!String.IsNullOrEmpty(frmSearch.txtMinQty.Text)) criteria.Add("min_qty", frmSearch.txtMinQty.Text);
            //if (!String.IsNullOrEmpty(frmSearch.txtHppAwal.Text)) criteria.Add("hpp_awal", frmSearch.txtHppAwal.Text);
            //if (!String.IsNullOrEmpty(frmSearch.txtHargaJual.Text)) criteria.Add("min_qty", frmSearch.txtHargaJual.Text);
            //if (null != (frmSearch.cboBrand.SelectedItem)) criteria.Add("Brand.brand_serial", (frmSearch.cboBrand.SelectedItem as BrandDTO).brand_serial);
            //if (null != (frmSearch.cboKelompok.SelectedItem)) criteria.Add("KelompokPersediaan.kelompok_persediaan_serial", (frmSearch.cboKelompok.SelectedItem as KelompokPersediaanDTO).kelompok_persediaan_serial);
            //string expression = string.Empty;
            //if (frmSearch.rblOr.IsChecked ?? false) expression = "OR"; else expression = "AND";
            //GroupSearch(criteria, expression);
        }

        private void GroupSearch(Dictionary<String, Object> criteria, string expression)
        {
            frmSearch.DialogResult = true;
            IsBusy = true;
            Complete(this);
            client.GetListByCriteriaCompleted += client_GetListByCriteriaCompleted;
            client.GetListByCriteriaAsync(criteria, expression, 1);
        }

        private void client_GetListByCriteriaCompleted(object sender, GetListByCriteriaCompletedEventArgs e)
        {
            Warehouses = new PagedCollectionView(e.Result);
            RecordCount = e.recordCount;
            CreatePageNumber();
            IsBusy = false;
        }


        private void CreatePageNumber()
        {
            Pages = new ObservableCollection<int>();
            for (int i = 0; i < RecordCount; i++)
            {
                Pages.Add(i);
            }
            PageSources = new PagedCollectionView(Pages);
        }


        private void PageIndexChanged(Object pageIndex)
        {
            //Jika Pertama kali jangan di Getlagi
            Warehouse = null;
            if (Warehouses != null && CurrentPage != (int) pageIndex)
            {
                CurrentPage = (int) pageIndex;
                if (String.IsNullOrEmpty(PropertySort))
                    GetList((int) pageIndex + 1, null);
                else GetList((int) pageIndex + 1, PropertySort);
            }
        }


        public bool CanPageIndexChanged(Object param)
        {
            return true;
        }


        public bool CanSave(Object param)
        {
            return true;
        }


        public bool CanNew(Object param)
        {
            return true;
        }

        public bool CanEdit(Object param)
        {
            return true;
        }


        public bool CanUnload(Object param)
        {
            return true;
        }


        public bool CanSearch(Object param)
        {
            return true;
        }

        public bool CanSearchResult(Object param)
        {
            return true;
        }


        public void Release(Object param)
        {
            param = null;
            Warehouse = null;
            OrderType = null;
            PropertySort = null;
            mode = Mode.Idle;
        }


        public void Refresh()
        {
            if (Warehouses == null)
                GetList(1, null);
            else
                Complete(this);
        }
    }

    public class WarehouseWrapViewModel : ViewModelBase
    {
        private readonly WarehouseServicesClient client;

        public WarehouseWrapViewModel()
        {
            if (!DesignerProperties.IsInDesignTool)
            {
                EditCommand = new DelegateCommand(Edit, CanEditCommand);
                DeleteCommand = new DelegateCommand(Delete, CanDeleteCommand);
                client = new WarehouseServicesClient();
            }
        }

        public Warehouse Warehouse { get; set; }
        public ICommand EditCommand { get; set; }
        public ICommand DeleteCommand { get; set; }


        public bool CanEditCommand(Object param)
        {
            return true;
        }

        public bool CanDeleteCommand(Object param)
        {
            return true;
        }


        public void Edit(Object param)
        {
            WarehouseViewModel.EditWarehouse(param);
        }

        public void Delete(Object param)
        {
            client.DeleteCompleted += client_DeleteCompleted;
            client.DeleteAsync((Warehouse) param);
        }

        private void client_DeleteCompleted(object sender, DeleteCompletedEventArgs e)
        {
            client.DeleteCompleted -= client_DeleteCompleted;
            MessageBox.Show("Delete Success!");
            WarehouseViewModel.mode = Mode.Idle;
            var VM = new WarehouseViewModel();
        }
    }
}